from django.contrib import auth
from django.http import HttpResponse
from django.http import Http404
from django.template import Context, loader
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Choice, Poll
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def index(request):
	template_var = {"welcome_msg": "Welcome Guest!"}
	if request.user.is_authenticated():
		template_var["welcome_msg"] = "You are welcome, %s" % request.user.username
	return render_to_response("accounts/welcome.html", template_var, context_instance=RequestContext(request))
	pass

def register(request):
	if request.method == 'POST':
		form = UserCreationForm(request.POST)
		if form.is_valid():
			new_user = form.save()
			return HttpResponseRedirect("accounts/index")
	else:
		form = UserCreationForm()
	initialData = {'form': form}
	csrfContext = RequestContext(request, initialData)
	return render_to_response("registration/register.html", csrfContext)

def login(request):
	username = request.POST.get('username', '')
	password = request.POST.get('password', '')
	user = auth.authenticate(username=username, password=password)
	if user is not None and user.is_active:
		auth.login(request, user)
		return HttpResponseRedirect('/accounts/loggedin')
	else:
		return HttpResponseRedirect('/accounts/invalid')

def logout(request):
	auth.logout(request)
	return HttpResponseRedirect('/accounts/index')
